<template>
  <div class="body">
    <Modal
      fullscreen
      width="1200"
      class="modalClass"
      v-model="modal"
      title="车辆历史轨迹展示">
      <div class="opt-area-02">
        <div class="left-con">
          <div class="input-frame" style="width: 164px">
            <Input disabled type="text" placeholder="车牌号" style="width: 164px" v-model="params.vehicleNo"/>
          </div>
          <div class="input-frame" style="width: 164px">
            <DatePicker type="datetime" v-model="params.start" format="yyyy-MM-dd HH:mm:ss" placeholder="选择开始时间" style="width: 164px"></DatePicker>
          </div>
          <div class="input-frame" style="width: 164px">
            <DatePicker type="datetime" v-model="params.end" format="yyyy-MM-dd HH:mm:ss" placeholder="选择结束时间" style="width: 164px"></DatePicker>
          </div>
          <Button type="primary" @click="searchDate" :loading="buttonLoading">查询轨迹</Button>
        </div>
      </div>
      <div id="container" :style="{height:offsetheight+'px'}"></div>
    </Modal>
  </div>
</template>

<script>
import {
  datetime2str,
  getVehiclePathByDate
} from '../../api/eventlist'
import img from '../../../src/assets/images/carNew.png'
import { toTmapLatLng } from '@/libs/gpsConvert'
export default {
  name: 'aMapIndex',
  data () {
    return {
      buttonLoading: false,
      modal: false,
      offsetheight: document.documentElement.clientHeight - 210,
      map: null,
      dataList: [],
      max: 500,
      navgtrSpeed: 100000, // 播放速度
      navgtr: '',
      img,
      // params: {
      //   vehicleNo: '辽GJ8607',
      //   vehicleColor: '2',
      //   start: '2022-03-31 05:52:16',
      //   end: '2022-03-31 23:52:16'
      // },
      params: {
        vehicleNo: '',
        vehicleColor: '',
        start: '',
        end: ''
      }
    }
  },
  methods: {
    initMap () {
      this.map = new AMap.Map('container', {
        resizeEnable: true,
        center: [123.412581, 41.805853],
        zoom: 9
      })
    },
    isSupportCanvas () {
      let elem = document.createElement('canvas')
      return !!(elem.getContext && elem.getContext('2d'))
    },
    creatPathSimplifier () {
      let _this = this
      AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], function (PathSimplifier, $) {
        if (!PathSimplifier.supportCanvas) {
          alert('当前环境不支持 Canvas！')
          return
        }
        var pathSimplifierIns = new PathSimplifier({
          zIndex: 100,
          map: _this.map,
          getPath: function (pathData, pathIndex) {
            return pathData.path
          },
          getHoverTitle: function (pathData, pathIndex, pointIndex) {
            console.log('pathData', pointIndex)
            if (pointIndex >= 0) {
              // point
              // return pathData.name + '，点：' + pointIndex + '/' + pathData.path.length
              return _this.dataList[pointIndex].date
            }

            // return pathData.name + '，点数量' + pathData.path.length
          },
          renderOptions: {
            renderAllPointsIfNumberBelow: 100, // 绘制路线节点，如不需要可设置为-1
            keyPointStyle: {
              radius: 6, // 点的半径
              fillStyle: 'red', // 填充色，比如 red, rgb(255,0,0), rgba(0,0,0,1)等
              strokeStyle: 'red', // 描边色
              lineWidth: 0 // 描边宽度
            },
            // 轨迹线的样式
            pathLineStyle: {
              strokeStyle: 'red',
              lineWidth: 5,
              dirArrowStyle: true
            }
          }
        })
        window.pathSimplifierIns = pathSimplifierIns
        var pathList = []
        let data = _this.dataList
        data.forEach(item => {
          let a = toTmapLatLng(item.lat, item.lon)
          pathList.push(new AMap.LngLat(a.lng, a.lat))
        })
        pathSimplifierIns.setData([{
          name: '轨迹',
          path: pathList
        }])

        // 对第一条线路（即索引 0）创建一个巡航器
        var navg1 = pathSimplifierIns.createPathNavigator(0, {
          loop: true, // 循环播放
          speed: 40000, // 巡航速度，单位千米/小时，
          pathNavigatorStyle: {
            initRotateDegree: 120,
            // autoRotate: true,
            width: 30,
            height: 30,
            content: PathSimplifier.Render.Canvas.getImageContent(img), // 自定义巡航器样式
            strokeStyle: null,
            fillStyle: null
          }
        })
        navg1.start()
      })
    },
    createMaker () {
      var marker = new AMap.Marker({
        iconLabel: '起', // 文字描述
        position: new AMap.LngLat(this.dataList[0].lon, this.dataList[0].lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        title: '起',
        iconStyle: {
          src: '//webapi.amap.com/theme/v1.3/markers/b/mark_b.png',
          style: {
            width: '20px',
            height: '30px',
            color: '#f5f5f5'
          }
        }
      })
      this.map.add(marker)
    },
    async getVehiclePathByDate () {
      let data = {
        vehicleNo: this.params.vehicleNo,
        vehicleColor: this.params.vehicleColor,
        start: datetime2str(this.params.start),
        end: datetime2str(this.params.end)
      }
      return new Promise(resolve => {
        getVehiclePathByDate(data).then(ret => {
          if (ret.data.errcode === 0) {
            return resolve(ret.data.data)
          } else {
            this.$Notice.error({ title: '失败', desc: ret.data.errmsg })
          }
        })
      })
    },
    play () {
      this.navgtr.start()
    },
    searchDate () {
      if (this.params.start && this.params.end) {
        let beginTime = datetime2str(this.params.start)
        let endTime = datetime2str(this.params.end)
        let dateBegin = new Date(beginTime)
        let dateEnd = new Date(endTime)
        if (dateBegin.getTime() > dateEnd.getTime()) {
          this.$Notice.error({ title: '查询失败', desc: '开始时间不能大于结束时间' })
          return
        }
        let dateDiff = dateEnd.getTime() - dateBegin.getTime()
        if (dateDiff >= 24 * 3600 * 1000) {
          this.$Notice.error({ title: '查询失败', desc: '检索期间不能超过1天' })
          return
        }
      }
      this.buttonLoading = true
      this.getVehiclePathByDate().then(ret => {
        console.log(ret)
        if (ret.error) {
          this.$Notice.error({ title: '查询失败', desc: ret.errorMsg })
          return
        }
        let data = ret.datas
        if (data.length !== 0) {
          this.dataList = data
          this.map && this.map.destroy()
          setTimeout(() => {
            this.initMap()
            this.creatPathSimplifier()
          }, 1000)
        } else {
          this.$Notice.error({ title: '查询失败', desc: '未查询到车辆轨迹！' })
        }
      })
      this.buttonLoading = false
    },
    init (e) {
      console.log('init', e)
      this.params.vehicleNo = e.car_number
      this.params.vehicleColor = e.chepai_color
      setTimeout(() => {
        this.initMap()
      }, 1000)
      this.modal = true
    }
  },
  watch: {
    modal (val) {
      if (!val) {
        this.map && this.map.destroy()
      }
    }
  },
  beforeDestroy () {
    this.map && this.map.destroy()
  }
}
</script>

<style scoped>
#container {
  padding: 0;
  /*// width: 100%;*/
  /*//height: 400px;*/
}
.input-card .btn {
  margin-right: 1.2rem;
  width: 9rem;
}
.demo-spin-container{
  display: inline-block;
  width: 100%;
  /*//height: 400px;*/
  position: relative;
  /*//border: 1px solid #eee;*/
}
.opt-area-02 {
  display: flex;
  align-items: center;
  flex-direction: column;
  border: 1px solid #abdcff;
  background-color: #f0faff;
  padding: 8px 16px 8px 16px;
  border-radius: 4px;
  margin-bottom: 10px;
}
.input-frame {
  width: 120px;
  margin-right: 10px;
  float: left;
}
.opt-area-02 .left-con {
  font-size: 14px;
  width: 100%;
}

.opt-area-02 .left-con span {
  font-weight: bold;
}
</style>
